package com.app.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.app.dao.BaseDAO;
import com.app.dao.BookDAO;
import com.app.dao.entity.Book;

public class App {
	public static void main(String[] args) throws Exception {
		String BookInput = "";
		InputStreamReader converter = new InputStreamReader(System.in);
		BufferedReader BR = new BufferedReader(converter);
		String bookTitle = "";
		String bookUrl = "";
		System.out.println("Hibirnate + MSSQL!!!!!");
		BookDAO bookDAO = new BookDAO();

		try {
			bookDAO.beginTransaction();
			while (!(BookInput.equals("0"))) {
				System.out.println("1. Book properties");
				System.out.println("0. Exit");

				BookInput = BR.readLine();
				if ("1".equals(BookInput)) {

					System.out.print(" Enter Book Title: ");
					bookTitle = BR.readLine();
					System.out.print(" Enter Book URL: ");
					bookUrl = BR.readLine();
					Book book = bookDAO.createBook(bookTitle, bookUrl);
					System.out.println("Book created. Title: "
							+ book.getBookTitle() + " URL: "
							+ book.getBookUrl());
					

					try {
						bookDAO.saveOrUpdate(book);// ?
						Long id = new Long(18);
						Book oldBook = bookDAO.findByID(id);// ?
						if (oldBook != null) {
							oldBook.setBookTitle("NEW");
							bookDAO.saveOrUpdate(oldBook);
						}
					} catch (Exception e) {
						System.out.println("Book is Title" + bookTitle
								+ " already exists.");
					}

				}
			}
			bookDAO.commiteTransaction();
		
		} catch (HibernateException ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			bookDAO.rollbackTransaction();
			throw new ExceptionInInitializerError(ex);
		}
	}
}
